import React, {AsyncStorage, Component} from "react";
import {Toast} from "antd-mobile";
import {restApiRequest} from "../Api/Public";
import Modal from "react-modal";
import logo from "../../../images/pic_login_headpic.png";
import BlockButton from "../../Public/Components/BlockButton";

const customStyles = {
    overlay: {
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.4)',
        zIndex: 999
    },
    content: {
        top: '47%',
        left: '50%',
        right: 'auto',
        bottom: 'auto',
        marginRight: '-50%',
        transform: 'translate(-50%, -50%)',
        padding: 0,
        backgroundColor: null,
        border: null
    }
};

const codeTime = 60;
export default class Login extends Component {

    constructor(props, context) {
        super(props, context);

        this.state = {
            phoneText: '',//手机号
            smsCode: null,//验证码
            timerCount: codeTime,//倒计时
            showButton: true,//获取验证码
            modalIsOpen: true
        };
        this.interval;
        this.openModal = this.openModal.bind(this);
        this.closeModal = this.closeModal.bind(this);

    }

    //进行储存数据
    saveStorage(key, value) {
        try {
            localStorage.setItem(key, value);
        } catch (error) {
            console.log(error.message);
        }
    }

    openModal() {
        this.setState({modalIsOpen: true});
    }

    closeModal() {
        if (this.props.onClosedCallback != undefined) {
            this.props.onClosedCallback();
        }
        this.setState({modalIsOpen: false});
    }

    //获取验证码
    getSmsCode() {
        let phoneText = this.state.phoneText.replace(/\s+/g, "");
        if (phoneText == null || phoneText.length != 11) {
            Toast.info('请输入完整手机号');
            return;
        }

        let reg = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
        if (!reg.test(phoneText)) {
            Toast.info('手机号格式错误');
            return;
        }
        //获取验证码不可点击
        this.setState({
            showButton: false,
        });

        let sms_code_url = '/shop/api/sendSmsCode';       //获取短信验证码地址
        let paramer = {sms_type: 'login', cell_number: phoneText};
        let jsonData = restApiRequest.getSign(paramer);

        restApiRequest.fetchp(sms_code_url, jsonData).then((response) => {
            if (!response.ok) {
                let error = new Error(response.statusText);
                error.response = response;
                throw error;
            } else {
                return response.json();
            }
        }).then((response_json) => {
            console.log(response_json)
            let res_code = response_json.code;
            if (res_code === '0000') {
                this.interval = setInterval(() => {
                    let timer = this.state.timerCount - 1;
                    if (timer === 0) {
                        this.interval && clearInterval(this.interval);
                        this.setState({
                            showButton: true,
                            timerCount: codeTime,
                        })
                    } else {
                        this.setState({
                            timerCount: timer,
                        })
                    }
                }, 1000);
            } else {
                this.setState({
                    showButton: true,
                    showText: false,
                });
                Toast.info(response_json.msg, 2);
            }
        }).catch((ex) => {
            this.setState({
                showButton: true,
                showText: false,
            });
            console.log(ex);
        });
    }

    //登录
    login(phoneText, smsCode) {
        console.log(phoneText);
        if (phoneText == null || phoneText.length != 11) {
            Toast.info('请输入完整手机号', 2);
            return;
        }

        let reg = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
        if (!reg.test(phoneText)) {
            Toast.info('手机号格式错误', 2);
            return;
        }

        let user_source = 0;

        if (smsCode == null || smsCode.length != 4) {
            Toast.info('请输入正确验证码q' + smsCode, 2);
            return;
        }

        let login_url = '/shop/api/login';       //用户登录
        let paramer = {sms_code: smsCode, cell_number: phoneText, user_source: user_source};
        let jsonData = restApiRequest.getSign(paramer);

        restApiRequest.fetchp(login_url, jsonData).then((response) => {
            if (!response.ok) {
                let error = new Error(response.statusText);
                error.response = response;
                throw error;
            } else {
                return response.json();
            }
        }).then((response_json) => {
            console.log(response_json)
            let res_code = response_json.code;
            if (res_code === '0000') {
                this.setState({visible: false});
                this.interval && clearInterval(this.interval);
                let responseData = response_json.data;
                this.saveStorage('sessionkey', responseData.sessionkey);
                this.saveStorage('cell_number', phoneText);
                this.saveStorage('user_id', responseData.user_id.toString());
                //登录成功后的回调
                if (this.props.onLoginCallback != undefined) {
                    this.props.onLoginCallback(responseData.sessionkey);
                }
            } else {
                Toast.info(response_json.msg);
            }
        }).catch((ex) => {
            console.log(ex);
        });
    }

    render() {
        return (
            <div>
                <Modal
                    ariaHideApp={false}
                    isOpen={this.state.modalIsOpen}
                    onRequestClose={this.closeModal}
                    style={customStyles}
                    contentLabel="login"
                >
                    <section className="login-wrap">
                        <section className="login-img-wrap">
                            <img src={logo} className="login-img"/>
                            <div className="login-img-placeholder"/>
                        </section>
                        <section className="login-content-wrap">
                            <p className="login-title">请您登录</p>
                            <section className="login-input-box">
                                <label>
                                    <svg>
                                        <use xlinkHref={'#icon-ico_mobile_login'}></use>
                                    </svg>
                                </label>
                                <input
                                    type="tel"
                                    placeholder="请输入手机号码"
                                    maxLength={11}
                                    value={this.state.phoneText}
                                    onChange={(e) => {
                                        this.setState({phoneText: e.target.value})
                                    }}
                                />
                            </section>
                            <div className="login-input-line"/>
                            <section className="login-input-box">
                                <label>
                                    <svg>
                                        <use xlinkHref={'#icon-ico_passcode_login'}></use>
                                    </svg>
                                </label>
                                <input
                                    type="tel"
                                    placeholder="请输入验证码"
                                    maxLength={4}
                                    onChange={(e) => {
                                        this.setState({smsCode: e.target.value})
                                    }}
                                />

                                {
                                    this.state.showButton ? <button className="login-yzm-default" type="button"
                                                                    onTouchStart={() => this.getSmsCode()}>获取验证码</button> :
                                        <button className="login-yzm-active"
                                                type="button">{this.state.timerCount + 's后重新获取'}</button>
                                }

                            </section>

                            <BlockButton
                                btnName={'下一步'}
                                bgColor={'#FFE227'}
                                btnHeight={'.96rem'}
                                btnWidth={'7.86rem'}
                                textColor={'#000'}
                                textSize={'.42rem'}
                                className={'login-btn'}
                                onPress={
                                    () => {
                                        let phoneText = this.state.phoneText.replace(/\s+/g, "");
                                        this.login(phoneText, this.state.smsCode)
                                    }
                                }
                            />

                        </section>
                    </section>

                </Modal>

            </div>

        )
    }
}
